package com.hk.commons.http.async;

import lombok.SneakyThrows;
import org.apache.hc.client5.http.HttpResponseException;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author kevin
 * @date 2019-8-9 13:04
 */
public abstract class AbstractFutureCallback implements FutureCallback<SimpleHttpResponse> {

    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    @SneakyThrows
    public void completed(SimpleHttpResponse response) {
        final var statusCode = response.getCode();
        var body = response.getBody();
        if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
            throw new HttpResponseException(statusCode, response.getReasonPhrase());
        }
        if (body.isText()) {
            handleText(body.getBodyText());
        } else {
            handleBytes(body.getBodyBytes());
        }
    }

    public abstract void handleText(String entity);

    public abstract void handleBytes(byte[] bytes);

    @Override
    public void failed(Exception ex) {
        log.error(ex.getMessage(), ex);
    }

    @Override
    public void cancelled() {
        //Not　Used.
    }
}
